package com.sunyard.utils.unionfrsutil;

import com.alipay.api.FileItem;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName: TestImgToBase64
 * @PackageName: com.sunyard.trade.test
 * @Deescription: TODO
 * @Author: zhix.huang
 * @Date: 2020/3/10 9:52
 * @Version: V1.0
 **/
public class TestImgToBase64 {


    /**
     * 本地图片转换成base64字符串
     *
     * @param imgFile 图片本地路径
     * @return
     * @author ZHANGJL
     * @dateTime 2018-02-23 14:40:46
     */
    public static String ImageToBase64ByLocal(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理


        InputStream in = null;
        byte[] data = null;

        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);

            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();

        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

    public static void main(String[] args) throws IOException {
        String url = "d:/Desktop/aaa.jpg";
        String str = ImageToBase64ByLocal(url);
        //System.out.println(str);

        FileItem fileItem = new FileItem(url);

        byte[] b = fileItem.getContent();
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String s = encoder.encode(b);
        //System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        System.out.println(s);


    }
}
